package com.zhentao.file.service.impl;

import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioConfigProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Date 2024/5/9 10:29
 * @Author xdm
 **/
@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
public class FileStorageServiceImpl implements FileStorageService {


    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfigProperties minioConfigProperties;


    @SneakyThrows
    @Override
    public String uploadImageFile(String fileName, InputStream inputStream) {

        //文件名的处理

        fileName = UUID.randomUUID()+ fileName;

        //文件的上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName) //文件名字
                .bucket(minioConfigProperties.getBucket())
                .contentType("image/jpg")
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        //url
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;
    }

    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        //文件名的处理

        fileName = UUID.randomUUID()+ fileName;

        //文件的上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName) //文件名字
                .bucket(minioConfigProperties.getBucket())
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        //url
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;
    }
}
